#!/usr/bin/env python

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import gdata.alt.appengine
import gdata.auth
import gdata.docs.service


class Greeting(db.Model):
    author = db.UserProperty()
    description = db.StringProperty(multiline = True)
    date = db.DateTimeProperty(auto_now_add = True)
    eventdate = db.DateTimeProperty(auto_now_add = True)
    title = db.StringProperty(multiline = False)
    location = db.GeoPtProperty();



class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("Logged in as %s - <a href=\"%s\">sign out</a>" %
                        (user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<a href=\"%s\">Sign in or register</a>." %
                        users.create_login_url("/"))

        #client = gdata.service.GDataService()
        client = gdata.docs.service.DocsService()
        gdata.alt.appengine.run_on_appengine(client)

        session_token = None
        # Find the AuthSub token and upgrade it to a session token.
        auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)
        auth_url = "."
        if auth_token:
            session_token = client.upgrade_to_session_token(auth_token)
        else:
            auth_url = client.GenerateAuthSubURL(
            'http://manageworktime.appspot.com/',
            ('http://docs.google.com/feeds/',), secure = False, session = True)

        if session_token:
            if users.get_current_user():
                client.token_store.add_token(session_token)
            else:
                client.current_token = session_token
            documents_feed = client.GetDocumentListFeed()
            # Loop through the feed and extract each document entry.
            for document_entry in documents_feed.entry:
                #Display the title of the document on the command line.
                print document_entry.title.text + '<br>'
        self.response.out.write(template.render('main.html', {'greeting':greeting, 'auth_url':auth_url}))

    def post(self):
        self.response.out.write('posted')

def main():
    application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug = True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
